package com.sptpc.qimoxiangmu.service;


import com.sptpc.qimoxiangmu.controller.request.ModelRequest;
import com.sptpc.qimoxiangmu.model.Type;
import com.sptpc.qimoxiangmu.model.Model;
import com.sptpc.qimoxiangmu.model.vo.ModelVo;
import com.sptpc.qimoxiangmu.repository.TypeRepository;
import com.sptpc.qimoxiangmu.repository.ModelRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ModelService {
    @Autowired
    private ModelRepository modelRepository;
    @Autowired
    private TypeRepository typeRepository;

    public Model save(ModelRequest typeRequest){
        Optional<Type> optionalType= typeRepository.findById(typeRequest.getTypeId());
        if (optionalType.isPresent()){
            Type category=optionalType.get();
            Model type=new Model();
            BeanUtils.copyProperties(typeRequest,type);
            type.setType(category);
            return modelRepository.save(type);
        }
        return null;
    }

    public List<Model> findAllModel() {
        return modelRepository.findAll();
    }

    public List<Model> findModelByTypeName(String type_name) {
        Optional<Type> optionalType=typeRepository.findByName(type_name);
        if(optionalType.isPresent()){
            Type type =optionalType.get();
            return modelRepository.findAllByModel(type);
        }
        return null;
    }


    public List<Model> findModelByTypeId(long category_id) {
        Optional<Type> optionalType=typeRepository.findById(category_id);
        if(optionalType.isPresent()){
            Type type =optionalType.get();
            return modelRepository.findAllByModel(type);
        }
        return null;
    }
//    //删除
//    public void deleteDrink(Long id ){
//        drinkRepository.deleteById(id);
//    }
//    //
    public Model update(ModelVo modelVo) {
        //业务逻辑
        Optional<Model> optionalModel=modelRepository.findById(modelVo.getId());
        if(optionalModel.isPresent()){
            Model model=optionalModel.get();
            Optional<Type> optionalType= typeRepository.findById(modelVo.getTypeId());
            if (optionalType.isPresent()){
                Type type=optionalType.get();
                BeanUtils.copyProperties(modelVo,model);
                model.setType(type);
                return modelRepository.saveAndFlush(model);
            }
        }
        return null;
    }
//    //根据id查询drink
//    public Model findDrinkById(Long id){
//        Optional<Model> optionalDrink=drinkRepository.findById(id);
//        if (optionalDrink.isPresent()){
//            return optionalDrink.get() ;
//        }
//        return null;
//    }
}
